<?php
// this php file impements the connection between objects shown in the application and the database tables
session_start();

if (!isset($_SESSION['user'])) {
    echo "<script > window.location.href='index.php';</script>";
}

require_once('./config.php');
require_once('./inc/database.php');
require_once('./inc/functions.php');
require_once('./class/class.phpmailer.php');
require_once('./class/class.user.php');
require_once('./class/class.project.php');
require_once('./class/class.task.php');
require_once('./class/class.project_access_details.php');
require_once('./class/class.permissions.php');
require_once('./class/class.comments.php');
require_once('./class/baseDB.php');
require_once('./class/class.customer.php');

/* * *********************************************************************************************************************** */
//update peoject class members and insert to the DB
if (isset($_POST['hid_new_project'])) {
    $new_project = new project();
    if (isset($_POST['name']))
        $new_project->project_name = mysql_escape_string($_POST['name']);
    if (isset($_POST['description']))
        $new_project->project_description = mysql_escape_string($_POST['description']);
    if (isset($_POST['start_date']))
        $new_project->project_start_date = project::ReverseDate($_POST['start_date']);
    if (isset($_POST['end_date']))
        $new_project->project_end_date = project::ReverseDate($_POST['end_date']);
    if (isset($_POST['customer']))
        $new_project->project_customer = mysql_escape_string($_POST['customer']);
    if (isset($_POST['type']))
        $new_project->project_type = $_POST['type'];
    if (isset($_POST['link']))
        $new_project->project_test_link = $_POST['link'];
    if (isset($_POST['test_link']))
        $new_project->project_link = $_POST['test_link'];

    if (isset($_POST['Quotation']))
        $new_project->Quotation = $_POST['Quotation'];
    if (isset($_POST['DateQuotation']))
        $new_project->DateQuotation = project::ReverseDate($_POST['DateQuotation']);
    if (isset($_POST['FinalPrice']))
        $new_project->FinalPrice = $_POST['FinalPrice'];
    if (isset($_POST['DateFinalPrice']))
        $new_project->DateFinalPrice = project::ReverseDate($_POST['DateFinalPrice']);
    $new_project->insert();

    $pad = new pad();
    $pad->project_id = $new_project->getid();
    if (isset($_POST['ftp_user']))
        $pad->ftp_user = mysql_escape_string($_POST['ftp_user']);
    if (isset($_POST['ftp_pass']))
        $pad->ftp_pass = mysql_escape_string($_POST['ftp_pass']);
    if (isset($_POST['ftp_address']))
        $pad->ftp_address = mysql_escape_string($_POST['ftp_address']);
    if (isset($_POST['db_name']))
        $pad->db_name = mysql_escape_string($_POST['db_name']);
    if (isset($_POST['db_user']))
        $pad->db_user = mysql_escape_string($_POST['db_user']);
    if (isset($_POST['db_pass']))
        $pad->db_pass = mysql_escape_string($_POST['db_pass']);
    if (isset($_POST['db_address']))
        $pad->db_address = mysql_escape_string($_POST['db_address']);
    if (isset($_POST['manager_user']))
        $pad->manager_user = mysql_escape_string($_POST['manager_user']);
    if (isset($_POST['manager_pass']))
        $pad->manager_pass = $_POST['manager_pass'];
    if (isset($_POST['manager_address']))
        $pad->manager_address = mysql_escape_string($_POST['manager_address']);
    if (isset($_POST['cp_user']))
        $pad->cp_user = mysql_escape_string($_POST['cp_user']);
    if (isset($_POST['cp_pass']))
        $pad->cp_pass = mysql_escape_string($_POST['cp_pass']);
    if (isset($_POST['cp_address']))
        $pad->cp_address = mysql_escape_string($_POST['cp_address']);
    $pad->insert();
    // permissions to the contact customer user  
    $user_contect = user::get_user_contects($new_project->project_customer);
    if ($user_contect != 0) {
        foreach ($user_contect as $SingleUserContact) {
            $new_permissions = new permissions();
            $new_permissions->project_id = $new_project->getid();
            $new_permissions->user_id = $SingleUserContact->getuser_id();
            $new_permissions->role_type = $SingleUserContact->role_type;
            $new_permissions->insert();
        }
    }
    /* upload project attachment */
    if (isset($_FILES['file_project'])) {
        $path = './upload/';
        $arr = array(
            "image/jpeg" => "jpeg",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "doc",
            "application/msword" => "doc",
            "application/pdf" => "pdf",
            "text/plain" => "txt",
            "application/vnd.ms-powerpoint" => "ppt",
            "application/vnd.openxmlformats-officedocument.presentationml.presentatio" => "pptx",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
            "application/vnd.ms-excel" => "xls"
        );
        $type = $_FILES["file_project"]["type"];
        if (!is_dir($path . $new_project->getid())) {
            mkdir($path . $new_project->getid());
        }
        $path.=$new_project->getid() . '/P-' . $new_project->getid() . '*-*' . $_FILES["file_project"]["name"];
        // echo $path;
        if (!move_uploaded_file($_FILES["file_project"]["tmp_name"], $path)) {
            echo 'הקובץ לא עלה';
        } else {
            $new_project->attachments = $path;
            $new_project->update();
        }
    } else {
        echo "no file";
    }
}
/* * ********************************************************************************* */
//update user class members and insert to the DB
if (isset($_POST['hid_new_user'])) {
    $new_user = new user();

    if (isset($_POST['name']))
        $new_user->user_name = mysql_escape_string($_POST['name']);
    if (isset($_POST['password']))
        $new_user->user_password = mysql_escape_string($_POST['password']);
    if (isset($_POST['customer']))
        $new_user->user_customer = mysql_escape_string($_POST['customer']);
    if (isset($_POST['mail']))
        $new_user->user_mail = $_POST['mail'];
    if (isset($_POST['role_type']))
        $new_user->role_type = $_POST['role_type'];
    if (isset($_POST['send_mail'])) {
        $new_user->send_mail = $_POST['send_mail'];
    } else {
        $new_user->send_mail = 0;
    }
    if (isset($_POST['Fname']))
        $new_user->Fname = $_POST['Fname'];
    if (isset($_POST['Lname']))
        $new_user->Lname = $_POST['Lname'];
    if (isset($_POST['pon']))
        $new_user->pon = $_POST['pon'];
    if (isset($_POST['mobile']))
        $new_user->mobile = $_POST['mobile'];
    if (isset($_POST['Employee-Friilnsr'])) {
        $new_user->Employee_Friilnsr = $_POST['Employee-Friilnsr'];
        $new_user->Portfolio = $_POST['Portfolio'];
    }
    $new_user->insert();

    //send email
    $content = ' <b>שלום רב</b>
	                <p> נוצר לך שם משתמש למערכת ה -CRM  של חברת ריסטרט בע"מ.</p>
				    <p> עם כניסתך למערכת תוכל:</p>
				    <p>* לפתוח פניות הקשורות למערכות שלך</p>
					<p>* לצפות בסטטוס הטיפול בפניות ולהגיב עליהם.</p>
					<p>שם משתמש:  ' . $new_user->user_name . ' </p>
					<p>סיסמא:  ' . $new_user->user_password . '</p>
					<p>קישור למערכת:  ' . $CRM_uri . '</p>
					<p>שימוש פורה,</p>
					<p>ריסטרט בע"מ.</p>
				  ';
    $mail = new PHPMailer();
    $mail->IsSMTP(); // use SMTP
    $mail->IsHTML(true);
    $mail->From = "restartit@email.com"; 
    $mail->AddAddress($new_user->user_mail); 
    $mail->Subject = "יצירת משתמש חדש"; 
    $mail->Body = $content;
    $mail->CharSet = 'UTF-8';

    if (!$mail->Send()) { 
        echo "Message was not sent";
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message has been sent";
    }
}
/* * ******************************************************************************** */
//update customer class members and insert to the DB
if (isset($_POST['hid_new_customer'])) {
    $name = mysql_escape_string($_POST['name']);
    $status_customer = $_POST['status_customer'];
    $LTD = $_POST['LTD'];
    $Address = mysql_escape_string($_POST['Address']);
    $pon = $_POST['pon'];
    $PrefixPon = $_POST['PrefixPon'];
    $fax = $_POST['fax'];
    $PrefixFax = $_POST['PrefixFax'];
    $site = mysql_escape_string($_POST['site']);
    $LineBusiness = mysql_escape_string($_POST['LineBusiness']);
    $Arrived = mysql_escape_string($_POST['Arrived']);
    $notice = mysql_escape_string($_POST['notice']);
    $status = $_POST['status'];
    $user_contects = "";
    //$st=sprintf("INSERT INTO `customer`(`customer_name`,`Active`) VALUES ('$name',1)");
    // $query=mysql_query($st)or die(mysql_error().' '.$st);
    $customer = new customer("", $name, $status_customer, $LTD, $Address, $PrefixPon . '-' . $pon, $PrefixFax . '-' . $fax, $site, $LineBusiness, $Arrived, $notice, $status, $user_contects, 1);
    $customer->Insert();
}
/* * *********************************************************************************** */
//update exiting project members
if (isset($_POST['hid_edit_project'])) {
    $new_project = new project();
    $new_project->getby_id($_POST['hid_edit_project']);

    if (isset($_POST['name']))
        $new_project->project_name = mysql_escape_string($_POST['name']);
    if (isset($_POST['description']))
        $new_project->project_description = mysql_escape_string($_POST['description']);
    if (isset($_POST['start_date']))
        $new_project->project_start_date = project::ReverseDate($_POST['start_date']);
    if (isset($_POST['end_date']))
        $new_project->project_end_date = project::ReverseDate($_POST['end_date']);
    if (isset($_POST['customer']))
        $new_project->project_customer = mysql_escape_string($_POST['customer']);
    if (isset($_POST['type']))
        $new_project->project_type = $_POST['type'];
    if (isset($_POST['link']))
        $new_project->project_test_link = $_POST['test_link'];
    if (isset($_POST['test_link']))
        $new_project->project_link = $_POST['link'];
    if (isset($_POST['active'])) {
        $new_project->project_active = $_POST['active'];
    } else {
        $new_project->project_active = 0;
    }
    if (isset($_POST['project_status']))
        $new_project->project_status = $_POST['project_status'];

    if (isset($_POST['Quotation']))
        $new_project->Quotation = $_POST['Quotation'];
    if (isset($_POST['DateQuotation'])) {
        if ($_POST['DateQuotation'] != "")
            $new_project->DateQuotation = project::ReverseDate($_POST['DateQuotation']);
    }
    if (isset($_POST['FinalPrice']))
        $new_project->FinalPrice = $_POST['FinalPrice'];
    if (isset($_POST['DateFinalPrice'])) {
        if ($_POST['DateFinalPrice'] != "")
            $new_project->DateFinalPrice = project::ReverseDate($_POST['DateFinalPrice']);
    }

    if (isset($_POST['SelCanceled'])) {
        if ($_POST['SelCanceled'] == 'none') {
            $new_project->Canceled = 'none';
        } else {
            $new_project->Canceled = $_POST['SelCanceled'] . ',' . $_POST['TextCanceled'];
        }
    }

    $new_project->update();
    $pad = new pad();
    $pad->project_id = $new_project->getid();
    if (isset($_POST['ftp_user']))
        $pad->ftp_user = mysql_escape_string($_POST['ftp_user']);
    if (isset($_POST['ftp_pass']))
        $pad->ftp_pass = mysql_escape_string($_POST['ftp_pass']);
    if (isset($_POST['ftp_address']))
        $pad->ftp_address = mysql_escape_string($_POST['ftp_address']);
    if (isset($_POST['db_name']))
        $pad->db_name = mysql_escape_string($_POST['db_name']);
    if (isset($_POST['db_user']))
        $pad->db_user = mysql_escape_string($_POST['db_user']);
    if (isset($_POST['db_pass']))
        $pad->db_pass = mysql_escape_string($_POST['db_pass']);
    if (isset($_POST['db_address']))
        $pad->db_address = mysql_escape_string($_POST['db_address']);
    if (isset($_POST['manager_user']))
        $pad->manager_user = mysql_escape_string($_POST['manager_user']);
    if (isset($_POST['manager_pass']))
        $pad->manager_pass = mysql_escape_string($_POST['manager_pass']);
    if (isset($_POST['manager_address']))
        $pad->manager_address = mysql_escape_string($_POST['manager_address']);
    if (isset($_POST['cp_user']))
        $pad->cp_user = mysql_escape_string($_POST['cp_user']);
    if (isset($_POST['cp_pass']))
        $pad->cp_pass = mysql_escape_string($_POST['cp_pass']);
    if (isset($_POST['cp_address']))
        $pad->cp_address = mysql_escape_string($_POST['cp_address']);
    $pad->update();
    /* change or add file to project */
    if (isset($_FILES['file_project_edit_upload'])) {
        $len = sizeof($_FILES['file_project_edit_upload']['name']);
        $arrAtt = explode(',', $new_project->attachments);
        $path = './upload/';
        $counter_file = 0;
        $temp_attachments = "";
        if (!is_dir($path . $new_project->getid())) {
            mkdir($path . $new_project->getid());
        }
        for ($i = 0; $i < $len; $i++) {
            $path = './upload/';
            $arr = array(
                "image/jpeg" => "jpeg",
                "image/png" => "png",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "doc",
                "application/msword" => "doc",
                "application/pdf" => "pdf",
                "text/plain" => "txt",
                "application/vnd.ms-powerpoint" => "ppt",
                "application/vnd.openxmlformats-officedocument.presentationml.presentatio" => "pptx",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
                "application/vnd.ms-excel" => "xls"
            );
            if ($_FILES['file_project_edit_upload']['name'][$i] != "") {


                if (file_exists($arrAtt[$i])) {
                    unlink($arrAtt[$i]);
                }


                $type = $_FILES["file_project_edit_upload"]["type"][$i];
                $path.=$new_project->getid() . '/P-' . $counter_file . '*-*' . $_FILES["file_project_edit_upload"]["name"][$i];

                //echo $path;exit;
                if (!move_uploaded_file($_FILES["file_project_edit_upload"]["tmp_name"][$i], $path)) {
                    echo 'הקובץ לא עלה';
                } else {//file was added
                    $counter_file++; 
                    if ($i == 0) {
                        $temp_attachments.= $path;
                    } else {
                        $temp_attachments.= ',' . $path;
                    }
                }
            }
            else {//if not exist
                $counter_file++;
                if ($i == 0) {
                    $temp_attachments.= $arrAtt[$i];
                } else {
                    $temp_attachments.= ',' . $arrAtt[$i];
                }
            }
        }
    } else {
        echo "no file";
    }
    if (isset($_FILES['file_project_edit_upload_new'])) {
        $len = sizeof($_FILES['file_project_edit_upload_new']['name']);
        $path = './upload/';

        if (!is_dir($path . $new_project->getid())) {
            mkdir($path . $new_project->getid());
        }
        for ($i = 0; $i < $len; $i++) {
            $path = './upload/';
            $arr = array(
                "image/jpeg" => "jpeg",
                "image/png" => "png",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "doc",
                "application/msword" => "doc",
                "application/pdf" => "pdf",
                "text/plain" => "txt",
                "application/vnd.ms-powerpoint" => "ppt",
                "application/vnd.openxmlformats-officedocument.presentationml.presentatio" => "pptx",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
                "application/vnd.ms-excel" => "xls"
            );
            if ($_FILES['file_project_edit_upload_new']['name'][$i] != "") {


                $type = $_FILES["file_project_edit_upload_new"]["type"][$i];
                $path.=$new_project->getid() . '/P-' . $counter_file . '*-*' . $_FILES["file_project_edit_upload_new"]["name"][$i];

                // echo $path;
                if (!move_uploaded_file($_FILES["file_project_edit_upload_new"]["tmp_name"][$i], $path)) {
                    echo 'הקובץ לא עלה';
                } else {// file was uploaded
                    $counter_file++;
                    if ($i == 0 && $new_project->attachments == "") {
                        $temp_attachments.= $path;
                    } else {
                        $temp_attachments.= ',' . $path;
                    }
                }
            }//end if file
        }//end for
    }//end if isset
    $new_project->attachments = $temp_attachments;

    //echo $new_project->attachments;exit;
    $new_project->update();

    //update user permission if given inside edit project screen
    if (isset($_POST['list'])) {
        foreach ($_POST['list'] as $IdUser) {
            $user = new user();
            $user->getby_id($IdUser);
            if (permissions::is_permissions($IdUser, $new_project->getid()) == 0) {
                $new_permissions = new permissions();
                $new_permissions->user_id = $user->getuser_id();
                $new_permissions->project_id = $new_project->getid();
                $new_permissions->role_type = $user->role_type;
                $new_permissions->Insert();
            }
        }
    }
}


/* * ******************************************************************************************************* */
//update exiting class user members
if (isset($_POST['hid_edit_user'])) {
    $new_user = new user();
    $new_user->getby_id($_POST['hid_edit_user']);

    if (isset($_POST['name']))
        $new_user->user_name = mysql_escape_string($_POST['name']);
    if (isset($_POST['password']))
        $new_user->user_password = mysql_escape_string($_POST['password']);
    if (isset($_POST['customer']))
        $new_user->user_customer = mysql_escape_string($_POST['customer']);
    if (isset($_POST['mail']))
        $new_user->user_mail = $_POST['mail'];
    if (isset($_POST['role_type']))
        $new_user->role_type = $_POST['role_type'];
    if (isset($_POST['send_mail'])) {
        $new_user->send_mail = $_POST['send_mail'];
    } else {
        $new_user->send_mail = 0;
    }
    if (isset($_POST['user_active'])) {
        $new_user->user_active = $_POST['user_active'];
    } else {
        $new_user->user_active = 0;
    }
    if (isset($_POST['Fname']))
        $new_user->Fname = $_POST['Fname'];
    if (isset($_POST['Lname']))
        $new_user->Lname = $_POST['Lname'];
    if (isset($_POST['pon']))
        $new_user->pon = $_POST['pon'];
    if (isset($_POST['mobile']))
        $new_user->mobile = $_POST['mobile'];
    if (isset($_POST['Employee-Friilnsr'])) {
        $new_user->Employee_Friilnsr = $_POST['Employee-Friilnsr'];
        $new_user->Portfolio = $_POST['Portfolio'];
    }
    $new_user->update();
}
/* * ************************************************************************************************************* */
//update exiting class customer members
if (isset($_POST['hid_edit_customer'])) {
    $name = mysql_escape_string($_POST['name']);
    $status_customer = $_POST['status_customer'];
    $LTD = $_POST['LTD'];
    $Address = mysql_escape_string($_POST['Address']);
    $pon = $_POST['pon'];
    $PrefixPon = $_POST['PrefixPon'];
    $fax = $_POST['fax'];
    $PrefixFax = $_POST['PrefixFax'];
    $site = mysql_escape_string($_POST['site']);
    $LineBusiness = mysql_escape_string($_POST['LineBusiness']);
    $Arrived = mysql_escape_string($_POST['Arrived']);
    $notice = mysql_escape_string($_POST['notice']);
    $status = $_POST['status'];
    $user_contects = "null";
    $cid = $_POST['hid_edit_customer'];
    $customer = new customer();
    $customer->GetById($cid);
    $customer->Active = '0';
    if (isset($_POST['customer_active'])) {
        $customer->Active = $_POST['customer_active'];
    }

    $customer->customer_name = $name;
    $customer->TypeCustomer = $status_customer;
    $customer->LTD = $LTD;
    $customer->Address = $Address;
    $customer->Pon = $PrefixPon . '-' . $pon;
    $customer->Fax = $PrefixFax . '-' . $fax;
    $customer->Site = $site;
    $customer->LineBusiness = $LineBusiness;
    $customer->Arrived = $Arrived;
    $customer->notice = $notice;
    $customer->Status = $status;
    $customer->UserContacts = $user_contects;
    $customer->Update();
    if (isset($_POST['list'])) {
        foreach ($_POST['list'] as $IdUser) {
            $user = new user();
            $user->getby_id($IdUser);
            $user->role_type = 4;
            $user->Update();
        }
    }
}
/* * ***************************************************************************************************************** */
?>
<script> window.location = 'main.php?admin';</script>